package com.itheima.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.JwtUtil;
import com.itheima.reggie.common.SmsTemplate;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Map;
import java.util.Random;

//用户
@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    //发送短信
    @Override
    public void sendMsg(String phone) {
        //1.生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        code="123456";//todo 产品上线之前，需要实现真实短信发送
        //2.发送短信
        //smsTemplate.sendSms(phone,code);
        log.info("短信发送成功:{}",code);
        //3.redis存储一份验证码，有效期5分钟
        redisTemplate.opsForValue().set(Constant.USER_CODE+phone,code, Duration.ofSeconds(300));
    }
    //登录注册
    @Override
    public String login(String phone, String code) {
        //1.校验验证码
        //1.1取出redis中的验证码
        String codeRedis = (String) redisTemplate.opsForValue().get(Constant.USER_CODE + phone);
        //1.2比较
        if(!StrUtil.equals(code,codeRedis)){//不一致
            throw new CustomException("验证码不正确");
        }
        //2.根据phone查询数据库
        //select * from user where phone =?;
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        User user = userMapper.selectOne(qw);
        //3.没查到，创建新用户

        if(user == null){
             user = new User();
             user.setPhone(phone);
             user.setStatus(1);
             //保存数据库
            userMapper.insert(user);
        }
        //4.老用户,制作token
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(map);
        //5.删除redis验证码
        redisTemplate.delete(Constant.USER_CODE+phone);
        //6.返回token
        return token;
    }
}
